#! /usr/bin/env Python
#coding:utf-8

import tornado.web
from methods import db
from base import BaseHandler

class IndexHandler(tornado.web.RequestHandler):
	def get(self):
		self.render("index.html")

class LoginHandler(tornado.web.RequestHandler):
	def get(self):
		self.render("login.html")


class RegisterHandler(tornado.web.RequestHandler):
	def get(self):
		self.render("register.html")
	
	def post(self):
		username = self.get_argument("username")
		password = self.get_argument("password")
		age = self.get_argument("age")
		sex = self.get_argument("sex")

		sql = 'INSERT INTO t_user (username, password, age, sex) VALUES ("%s", "%s", "%s", "%s")' % (username, password, age, sex)

		db.insert_data(sql)

		self.render("index.html")

class ConfirmFormHandler(tornado.web.RequestHandler):
	def get(self):
		post(self)
	def post(self):
		username = self.get_argument("username")
		sql = "select username from t_user"
		username_list = db.multiple_query(sql)
		for i in username_list:
			if username == i['username']:
				self.write("用户名已被占用！")
				break
			else:
				self.write("恭喜你，完美的用户名！")
				break

class AllowLoginHandler(BaseHandler):
	def post(self):
		username = self.get_argument("username")
		password = self.get_argument("password")


		sql = 'SELECT * FROM t_user WHERE username="%s" AND password="%s"' % (username, password)
		result = db.get_query(sql)
		if(result == None):
			self.write("用户名或密码错误！")
		else:
			self.set_current_user(username)
			self.write("0")
	
	def set_current_user(self, user):
		if user:
			self.set_secure_cookie('user', tornado.escape.json_encode(user), httponly=True, secure=True)
		else:
			self.clear_cookie("user")

	def get(self):
		post(self)